<template>
  <div>
    <template v-if="isLoading">
      <div class="flex flex-j-c box-border pt-22n min-100 box-border">
        <van-loading />
      </div>
    </template>
    <template v-else>
      <template v-if="isIn == 2">
        <Tip1 :userInfo="userInfo" @checkSelf="checkSelf"></Tip1>
      </template>
      <template v-else-if="isIn == 3">
        <Tip2 :userInfo="userInfo" @checkGroup="checkGroup"></Tip2>
      </template>
      <template v-else>
        <div class="box bg-image bgEA5752 overflow-y-auto box-border pb-50">
          <div class="px-28 box-border textfff pt-36 m-relative">
            <div>
              <dl class="flex flex-a-c">
                <dt class="w-98 h-98 flex-center">
                  <label
                    class="flex-center borderfff round-50-p bgce overflow-hidden"
                  >
                    <div class="w-42 h-50" v-if="!userInfo.wxHeadImg">
                      <van-image
                        width="100%"
                        height="100%"
                        fit="cover"
                        src="https://images.maishou88.com/admin/buyer_circle_sc/20231128/20231128101248_7738.png"
                      />
                    </div>
                    <van-image
                      v-else
                      width="100%"
                      height="100%"
                      fit="cover"
                      :src="userInfo.wxHeadImg"
                    />
                  </label>
                </dt>
                <dd class="ml-20 flex-1" @click="handleLogin(false)">
                  <p class="text-overflow-1 text-size-32">
                    {{ userInfo.name || "点我登陆" }}
                  </p>
                  <p class="text-size-26 mt-10">
                    {{
                      userInfo.name
                        ? userInfo.groupName
                        : "登陆后可享更多福利！！"
                    }}
                  </p>
                </dd>
              </dl>
              <div
                class="m-absolute text-size-24 flex-col r-0 t-40"
                @click="handleLogin(true)"
              >
                <p class="text-align-center" v-if="userInfo?.uuid">
                  uid: {{ userInfo.uuid }}
                </p>
                <p
                  class="mt-6 bgd14e49 flex-a-c h-46 line-h-46 round-l-20 px-20"
                >
                  <van-icon name="replay" />
                  <span class="ml-2">重新登录</span>
                </p>
              </div>
            </div>
            <!-- 单商品 -->
            <!-- <template v-if="goodsList.length == 1"> -->
            <template v-if="goodsList.length == 1">
              <div
                class="p-30 mt-40 round-16 bgfff"
                v-for="(item, index) in goodsList"
                :key="index"
              >
                <dl class="flex flex-a-c w-full">
                  <dt class="w-50n h-50n">
                    <van-image
                      width="100%"
                      height="100%"
                      fit="cover"
                      :src="item.goods.mainPic"
                    />
                  </dt>
                  <dd class="flex-1 ml-18 flex-col flex-j-b h-48n">
                    <p class="text-size-30 text333 text-overflow-2 line-h-40">
                      {{ item.goods.goodsTitle }}
                    </p>
                    <p class="text-size-26 textEA5752">
                      需邀请{{ item.invitation }}人在群
                    </p>
                    <p class="text-size-30 textEA5752">
                      现价：¥
                      {{
                        item.isFreeOfCharge
                          ? 0
                          : priceFormat(
                              item?.goods?.actualPrice,
                              item?.giftMoney
                            )
                      }}
                      <span class="text-size-24 textc6 ml-6 text-through"
                        >¥{{ item.goods.originalPrice }}</span
                      >
                    </p>
                  </dd>
                </dl>
                <div
                  class="mt-30"
                  @click="handleReceive(item.giftGrantConfigId, index)"
                >
                  <van-button
                    color="#EA5752"
                    size="large"
                    :loading="item.receiveLoading"
                    loading-text="领取中..."
                    :class="item.isEnd == 1 ? 'gray' : ''"
                  >
                    <span class="opacity-0">占</span>
                    <span>{{
                      !userInfo.name && !userInfo.wxHeadImg
                        ? "登录领取"
                        : item.isEnd == 1
                        ? "活动已结束"
                        : "立即领取"
                    }}</span>
                    <span class="opacity-0">位</span>
                  </van-button>
                </div>
              </div>
              <div
                class="p-40 round-16 text666 text-size-26 bgfff mt-30 line-h-36"
                v-if="userInfo.name && userInfo.groupName"
              >
                本兔单为独家商家合作单为【{{ userInfo.groupName }}】
                提供粉丝内部VIP专享!仅限制群内粉丝领取，转发无效!（与商家合作不易!望各位粉丝小伙伴多多对本群的支持!）
              </div>
            </template>
            <!-- 多商品 -->
            <div class="mt-30" v-else-if="goodsList.length > 1">
              <dl class="textfff text-align-center">
                <dt class="text-size-42">
                  -{{ dayjs().format("MM.DD") }}日福利购-
                </dt>
                <dd class="text-size-28 mt-20">
                  已邀请：{{ userInfo.invitedNum }}人
                </dd>
              </dl>
              <div
                class="p-30 mt-40 round-16 bgfff m-relative"
                v-for="(item, index) in goodsList"
                :key="index"
              >
                <dl class="flex flex-a-c w-full">
                  <dt class="w-50n h-50n">
                    <van-image
                      width="100%"
                      height="100%"
                      fit="cover"
                      :src="item.goods.mainPic"
                    />
                  </dt>
                  <dd class="flex-1 ml-18 flex-col flex-j-b h-48n">
                    <div class="text-size-30 text333 text-overflow-2 line-h-40">
                      {{ item.goods.goodsTitle }}
                    </div>
                    <p class="text-size-26 textEA5752">
                      需邀请{{ item.invitation }}人在群
                    </p>
                    <p class="text-size-30 textEA5752">
                      ¥
                      {{
                        item.isFreeOfCharge
                          ? 0
                          : priceFormat(
                              item?.goods?.actualPrice,
                              item?.giftMoney
                            )
                      }}
                      <span class="text-size-24 textc6 ml-6 text-through"
                        >¥{{ item.goods.originalPrice }}</span
                      >
                    </p>
                  </dd>
                  <div
                    class="m-absolute b-40 h-58 r-30"
                    @click="handleReceive(item.giftGrantConfigId, index)"
                  >
                    <van-button
                      round
                      size="small"
                      color="#EA5752"
                      :loading="item.receiveLoading"
                      :class="item.isEnd == 1 ? 'gray' : ''"
                      loading-text="领取中..."
                    >
                      <span class="opacity-0">占</span>
                      <span>{{
                        !userInfo.name && !userInfo.wxHeadImg
                          ? "登录领取"
                          : item.isEnd == 1
                          ? "活动已结束"
                          : "立即领取"
                      }}</span>
                      <span class="opacity-0">位</span>
                    </van-button>
                  </div>
                </dl>
              </div>
            </div>
            <div class="mt-30 px-10 pb-20 round-16 bgfff">
              <div
                class="line-h-90 border-b text-size-32 text333 text-align-center"
              >
                邀请明细
              </div>
              <div
                class="w-full pt-20 pb-10 text-size-26 text333 flex flex-a-c flex-j-b px-16 box-border"
              >
                <div class="flex-4 text-align-center">邀请时间</div>
                <div class="flex-5 text-align-center">被邀请人</div>
                <div class="flex-2 text-align-center">状态</div>
              </div>
              <div
                class="max-h-500 overflow-hidden overflow-y-auto"
                v-if="invitedList.length > 0"
              >
                <div
                  class="h-14n text-size-24 flex flex-a-c flex-j-a flex-j-b px-16 box-border"
                  v-for="(item, index) in invitedList"
                  :key="index"
                >
                  <div class="flex-4 text999 text-align-center">
                    {{ dayjs(item.createdAt).format("YY/MM/DD HH:mm") }}
                  </div>
                  <div class="flex-center flex-5 overflow-hidden">
                    <div class="w-40 h-40">
                      <van-image
                        width="100%"
                        height="100%"
                        fit="cover"
                        :src="item.wechatDetail.wxHeadImg"
                        round
                      />
                    </div>
                    <div
                      class="text333 w-fit h-full line-h-14n max-c ml-8 text-overflow-1"
                    >
                      {{ item.wechatDetail.name }}
                    </div>
                  </div>
                  <div class="flex-2 flex text-aize-26 text-align-center sss2">
                    <span style="color: #ea5752" v-if="item.status == 1"
                      >不在群</span
                    >
                    <span style="color: #40be33" v-else>在群</span>
                    <div
                      class="nowrap text-size-12 flex-center round-6 ml-4 p-2 sss"
                      :class="
                        item.status == 1
                          ? 'text999 border999'
                          : 'text40BE33 border40BE33'
                      "
                    >
                      {{ item.status == 1 ? "已失效" : "已生效" }}
                    </div>
                  </div>
                </div>
              </div>
              <van-empty description="暂无数据" v-else />
            </div>
            <div class="w-full h-20n"></div>
            <!-- 投诉 -->
            <div class="m-fixed complaint r--4 w-56 h-50n" @click="toComplaint">
              <van-image
                src="https://images.maishou88.com/admin/buyer_circle_sc/20231127/20231127175937_1583.png"
                width="100%"
                height="100%"
              ></van-image>
            </div>
          </div>
          <!-- 领取成功 -->
          <van-popup v-model:show="isShowSucces" round>
            <div class="w-150n box-border round-20 py-11n flex-center-col">
              <div class="w-138n h-153n">
                <van-image
                  src="https://images.maishou88.com/admin/buyer_circle_sc/20231127/20231127182451_2341.png"
                  width="100%"
                  height="100%"
                ></van-image>
              </div>
              <van-icon
                name="close"
                size="40px"
                color="#fff"
                :style="{ marginTop: '18px' }"
                @click="isShowSucces = false"
              />
            </div>
          </van-popup>

          <!-- 领取失败 -->
          <van-popup v-model:show="isShowfail" round>
            <div
              class="w-150n box-border round-20 py-11n flex-center-col bgfff"
            >
              <dl class="flex-center-col">
                <dt class="w-96 h-96">
                  <van-image
                    src="https://images.maishou88.com/admin/buyer_circle_sc/20231128/20231128095302_7248.png"
                    width="100%"
                    height="100%"
                  ></van-image>
                </dt>
                <dd class="text-center text-size-32">
                  <p
                    class="mt-42 text-size-38 text000 font-weight-500 text-align-center"
                  >
                    领取失败
                  </p>
                  <p class="mt-42 text666 text-align-center nowrap">
                    {{ `${isShowfailText.split("!")[0]}!` }}
                  </p>
                  <p class="text666 mt-20 text-align-center nowrap">
                    {{ isShowfailText.split("!")[1] }}
                  </p>
                  <div class="w-60-p">
                    <van-button
                      size="large"
                      color="#ffa64d"
                      @click="isShowfail = false"
                    >
                      我知道了
                    </van-button>
                  </div>
                </dd>
              </dl>
            </div>
          </van-popup>
        </div>
      </template>
    </template>
  </div>
</template>

<script setup>
import {
  getOpenIdBase,
  getOpenId,
  getWeChatInfoByOpenId,
  getGoodsListByOpenId,
  getWeChatInviteListByOpenId,
  receiveGoodsByOpenId,
  isBindGroupByOpenId,
  isInGroupByOpenId,
} from "@/api";
import Tip1 from "./Tip1.vue";
import Tip2 from "./Tip2.vue";
import { showToast, showConfirmDialog, Loading } from "vant";
import { getQueryString, copyText } from "@/utils/common";
import dayjs from "dayjs";

defineOptions({ name: "currentCallback" });

const appid = "wxdf48c27f2d58324d";
const u = navigator.userAgent;
const isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; //android终端
const router = useRouter();
const isShowfail = ref(false);
const isShowfailText = ref();
const isShowSucces = ref(false);
const isIn = ref();
const isLoading = ref(true);
let openId = undefined;
let groupId = undefined;
let giftGrantConfigId = undefined;
const userInfo = reactive({
  groupName: undefined,
  integral: undefined,
  invitedNum: undefined,
  name: undefined,
  openId: undefined,
  bindKeyword: undefined,
  uuid: undefined,
  wxHeadImg: undefined,
});

const goodsList = ref([]);
const invitedList = ref([]);

const priceFormat = (num1, num2) => {
  const num1F = num1 || 0;
  const num2F = num2 || 0;
  let subtraction = num1 - num2;
  if (subtraction < 0) subtraction = 0;
  let result = subtraction.toFixed(2);
  if (result == "0.00") result = 0;
  else if (result.endsWith("0")) result = result.slice(0, -1);
  return result;
};

// 判断是否在系统
const checkSelf = (tip = false) => {
  isBindGroupByOpenId({ openId })
    .then((res) => {
      isIn.value = 1;
    })
    .catch((err) => {
      isIn.value = 2;
    })
    .finally(() => {
      if (tip) {
        showToast("刷新成功");
      }
    });
};

// 判断是否在群
const checkGroup = () => {
  isInGroupByOpenId({ openId, groupId, giftGrantConfigId })
    .then((res) => {
      isIn.value = 1;
    })
    .catch((err) => {
      isIn.value = 3;
      showToast("刷新成功，您不在群里");
    });
};

// 点击重新登录
const handleLogin = (flag = false) => {
  if ((userInfo.name || userInfo.wxHeadImg) && !flag) return;
  const local = encodeURIComponent(
    `https://pdd.bkd.fit/#/currentCallback?type=1&groupId=${groupId}&giftGrantConfigId=${giftGrantConfigId}`
  );
  window.location.href =
    "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
    appid +
    "&redirect_uri=" +
    local +
    "&response_type=code&scope=snsapi_userinfo&connect_redirect=1#wechat_redirect";
};

onMounted(async () => {
  //首页跳转返回 IOS不兼容页面自动刷新问题
  if (!isAndroid) {
    window.onpageshow = function (event) {
      if (event.persisted) {
        window.location.reload();
      }
    };
  }
  const url = window.location.href;
  const urlArr = url.split("?");
  const code = getQueryString("code", urlArr[1]);
  groupId = getQueryString("groupId", urlArr[2]);
  giftGrantConfigId = getQueryString("giftGrantConfigId", urlArr[2]);
  const type = getQueryString("type", urlArr[2]);
  if (!!code) {
    let res = undefined;
    const api = type == 1 ? getOpenId : getOpenIdBase;
    api({ code })
      .then((res) => {
        openId = res?.openId;
        // 第一个replace可以去除对应参数，第二个是为了防止去除的参数是 ？ 后的第一个参数就会使href变为 ?&a=xxx
        const deleteUrlCode = url.replace(`code=${code}&`, "");
        window.history.replaceState(null, null, deleteUrlCode);
        getWeChatInfoByOpenId({
          openId,
          groupId,
          giftGrantConfigId,
        })
          .then((res2) => {
            Object.assign(userInfo, res2 ?? {});
            if (userInfo.wxHeadImg || userInfo.name) {
              checkSelf(false);
            }
            setTimeout(() => {
              isLoading.value = false;
            }, 200);
            getGoodsList();
            inviteList();
          })
          .catch((err2) => {
            isLoading.value = false;
            showToast(err2?.message + err2?.code + "用户信息");
          });
      })
      .catch((err) => {
        isLoading.value = false;
        showToast(err?.message + err?.code + "openId");
      });
  } else {
    if (type == 1) {
      handleLogin(true);
    } else {
      window.location.href = `https://pdd.bkd.fit/#/current?groupId=${groupId}&giftGrantConfigId=${giftGrantConfigId}`;
    }
  }
});

// 获取商品列表
const getGoodsList = () => {
  getGoodsListByOpenId({
    openId,
    groupId,
    giftGrantConfigId,
  })
    .then((res) => {
      const result = res ?? [];
      goodsList.value = result.map((item) => {
        return {
          ...item,
          receiveLoading: false,
        };
      });
    })
    .catch((err) => {
      showToast(err?.message + err?.code + "商品列表");
    });
};

// 获取邀请列表
const inviteList = () => {
  getWeChatInviteListByOpenId({
    openId,
    groupId,
    giftGrantConfigId,
  })
    .then((res) => {
      invitedList.value = res ?? [];
    })
    .catch((err) => {
      showToast(err?.message + err?.code + "邀请列表");
    });
};

// 领取商品
const handleReceive = (giftGrantConfigId, index, stop = false) => {
  if (!userInfo.name && !userInfo.wxHeadImg) return handleLogin(false);
  if (stop) return false;
  goodsList.value[index].receiveLoading = true;
  receiveGoodsByOpenId({
    openId,
    groupId,
    giftGrantConfigId,
  })
    .then((res) => {
      if (res.kl) {
        copyText(res.kl);
        isShowSucces.value = true;
      } else {
        showToast("商品不存在");
      }
    })
    .catch((err) => {
      if (err.code == 303) {
        isShowfailText.value = err.message;
        isShowfail.value = true;
      } else if (err.code == 301) {
        isIn.value = 2;
      } else if (err.code == 304) {
        isIn.value = 3;
      } else {
        showToast(err?.message + err?.code);
      }
    })
    .finally(() => {
      goodsList.value[index].receiveLoading = false;
      getGoodsList();
    });
};

const toComplaint = () => {
  router.push({
    path: "/complaint",
    state: { openId: openId },
  });
};
</script>

<style scoped lang="scss">
.bgffa64d {
  background: #ffa64d;
}
.bgEA5752 {
  background: #ea5752;
}
.textEA5752 {
  color: #ea5752;
}
.textc6 {
  color: #c6c6c6;
}
.borderfff {
  border: solid 1px #fff;
}
.bgce {
  background: #cecece;
}
.bgd14e49 {
  background: #d14e49;
}
.bg-image {
  background-image: url("https://images.maishou88.com/admin/buyer_circle_sc/20231127/20231127171553_8240.png");
  background-repeat: no-repeat;
  background-size: 100% auto;
}
.r--4 {
  right: -4px;
}
.complaint {
  top: 40%;
}
.border-b {
  border-bottom: solid 1px rgba(102, 102, 102, 0.2);
}
.max-h-500 {
  max-height: 500px;
}
.van-popup {
  background: transparent;
}
.text40BE33 {
  color: #40be33;
}
.border40BE33 {
  border: solid 1px #40be33;
}
.border999 {
  border: solid 1px #999;
}

.sss2 {
  transform: translate(6px, 0);
}
.sss {
  transform: translate(0, -10px);
}
:deep(.van-button--large) {
  height: 90px;
}
.w-80-p {
  width: 80%;
  margin: 0 auto;
  line-height: 44px;
  margin-top: 20px;
}
.w-60-p {
  width: 90%;
  margin: 50px auto 0;
}
.box {
  width: 100vw;
  height: 100vh;
}
.flex-5 {
  flex: 5;
}
.flex-3 {
  flex: 3;
}
.gray {
  opacity: 0.5 !important;
}
.max-c {
  max-width: calc(100% - 50px);
}
</style>
